#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define BUFFER_SIZE 4096

/* Analoga a toLower.
 * Si el caracter esta en mayúscula lo devuelve en minúscula, sino lo devuelve igual.
 */
unsigned char char_to_low(unsigned char c) {
	return (c >= 'A' && c <= 'Z') ? 'a' + (c - 'A') : c;
}
/* Analoga a strcmp. Toma dos cadenas a y b.
 * Devuelve un integer menor, igual o mayor que cero
 * si a es menor, igual o mayor a b respectivamente.
 */
int comparar(unsigned char * a, unsigned char * b) {
	int i = 0;
	char aux_a;
	char aux_b;
	while ((a[i] != '\0') && (b[i] != '\0')) {
		aux_a = char_to_low(a[i]);
		aux_b = char_to_low(b[i]);

		if (aux_a != aux_b)
			return aux_a - aux_b;
		i++;
	}

	aux_a = char_to_low(a[i]);
	aux_b = char_to_low(b[i]);
	return aux_a - aux_b;
}

/* 
 Lee un archivo (file) y guarda los datos en un arreglo de unsigned chars devolviendo
 el tamaño del arreglo
 */
unsigned char **loadArrayFromFile(int *arraySize, FILE * file) {
	unsigned char buf[30];
	unsigned char **text = 0;
	int wordCount = 0;
	int c = 0;

	int i = 0;

	while (c != EOF) {

		c = getc(file);

		if (((c >= 'a') && (c <= 'z')) || ((c >= 'A') && (c <= 'Z'))
				|| ((c >= '0') && (c <= '9'))) {
			{
				buf[i] = c;
				++i;
			}
		} else {

			buf[i] = '\0';
			if (i != 0) {
				++wordCount;
				unsigned char *aux = malloc(i + 1);
				strcpy((char*) aux, (char*) buf);
				if (!text)
					text = malloc(wordCount * sizeof(char*));
				else
					text = realloc(text, wordCount * sizeof(char*));
				text[wordCount - 1] = aux;
				i = 0;
			}
		}
	}
	(*arraySize) = wordCount;

	return text;
}

